package com.lvmama.rhino.web;

import com.github.pagehelper.PageInfo;
import com.lvmama.rhino.pojo.*;
import com.lvmama.rhino.pojo.base.BaseResponseVO;
import com.lvmama.rhino.service.CategoryChannelViewService;
import com.lvmama.rhino.service.ProductBranchViewService;
import com.lvmama.rhino.service.RegionProductManagerService;
import com.lvmama.rhino.service.StockService;
import com.lvmama.rhino.utils.*;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("stock")
public class StockController {
    @Autowired
    private StockService stockService;
    @Autowired
    private RegionProductManagerService regionProductManagerService;
    @Autowired
    private CategoryChannelViewService categoryChannelViewService;
    @Autowired
    private ProductBranchViewService productBranchViewService;
    
    private Logger log = Logger.getLogger(StockController.class);

    @RequestMapping("detail")
    public String detail(ModelMap model) {
        try {
            //生成日期
            String[] latestDays = DateUtil.getFutureDays(29,Constants.DESC);
            List<String> days = new ArrayList<>();
            for (String day : latestDays) {
                days.add(day.substring(5, 10));
            }
            String day = JSONConversionUtil.objToString(days);
            model.addAttribute("days", day);
            model.addAttribute("currentDays", days);
        } catch (Exception e) {
            log.error("detail error:{}" + e.getMessage(), e);
        }
        return "application/stock/stockDetail";
    }
    
    @RequestMapping("stockGather")
    public String stock(ModelMap model) {
    	try {
    		//生成日期
    		String[] latestDays = DateUtil.getFutureDays(29,Constants.DESC);
    		List<String> days = new ArrayList<>();
    		for (String day : latestDays) {
    			days.add(day.substring(5, 10));
    		}
    		String day = JSONConversionUtil.objToString(days);
    		model.addAttribute("days", day);
    		model.addAttribute("currentDays", days);
    	} catch (Exception e) {
    		log.error("detail error:{}" + e.getMessage(), e);
    	}
    	return "application/stock/stockGather";
    }

    @RequestMapping("detailSearch")
    @ResponseBody
    public BaseResponseVO<Long> detailSearch(@RequestBody StockDetailQuery query ) {
        //查询库存详情
        return getStockNumByQuery(query, false);
    }

    @RequestMapping("gatherSearch")
    @ResponseBody
    public BaseResponseVO<Long> gatherSearch(@RequestBody StockDetailQuery query ) {
        //查询库存详情
        return getStockNumByQuery(query, true);
    }

    private BaseResponseVO<Long> getStockNumByQuery(StockDetailQuery query, Boolean needRedis){
    	BaseResponseVO<Long> responseVo = new BaseResponseVO<>();
    	try {
			StockDetail stockDetail = null;
    		responseVo.setCode(1);
    		if (needRedis){
				stockDetail = stockService.selectStockDetailRedis(query).get(0);
			}else{
				stockDetail = stockService.selectStockDetail(query).get(0);
			}

            if (stockDetail == null){
            	responseVo.setCode(0);
            	responseVo.setMessage("数据不存在");
				return responseVo;
			}
            //获取对象所有的属性值放到集合中
            Field[] fields = stockDetail.getClass().getDeclaredFields();
            List<Long> stockNums = new ArrayList<>();
            if (fields == null || fields.length == 0){
            	responseVo.setCode(0);
            	responseVo.setMessage("服务异常");
				return responseVo;
			}
            for (Field field : fields) {
                field.setAccessible(true);
				String fieldName = field.getName();
				if(fieldName.startsWith("stock") && !fieldName.equals("stock1")){
					Long  stockNum = (Long) field.get(stockDetail);
					stockNums.add(stockNum);
				}else if (fieldName.startsWith("parDay")){
					responseVo.setMessage((String)field.get(stockDetail));
				}
            }

            responseVo.setDataList(stockNums);
            return responseVo;
        }catch (IllegalAccessException e){
            log.error("detail error:{}" + e.getMessage(), e);
        }
    	responseVo.setCode(0);
    	responseVo.setMessage("服务异常");
		return responseVo;
    }
    
    /**
     * 各类明细查询
     * @param query
     * @return
     */
    @RequestMapping("search")
    @ResponseBody
    public BaseResponseVO<StockDetail> search(@RequestBody StockDetailQuery query){
    	BaseResponseVO<StockDetail> responseVo = new BaseResponseVO<StockDetail>();
    	try {
    		List<StockDetail> list = this.stockService.selectStockDetail(query);
    		if (list == null || list.size() == 0){
    			responseVo.setCode(0);
    			responseVo.setMessage("数据不存在");
    			return responseVo;
    		}
    		responseVo.setCode(1);
    		responseVo.setDataList(list);
    		return responseVo;
		} catch (Exception e) {
			log.error("detail error:{}" + e.getMessage(), e);
		}
    	responseVo.setCode(0);
		responseVo.setMessage("服务异常");
    	return responseVo;
    }
	/**
	 * 导出汇总excel
	 * @param query
	 * @return
	 */
	@RequestMapping("exportStockGather")
	public void exportStockGather( StockDetailQuery query, HttpServletResponse response){
		List<StockDetail> list = null;
		//如果是大区先取分页中的数据
		if (query.getGroupByRegionname()){
			PageInfoUtil<StockDetail> page = this.stockService.selectStockDetailPageByRedis(query, 100);
			list = page.getList();
		}else {
			list = this.stockService.selectStockDetailRedis(query);
		}
		exportExcel(query, response, list, false);
	}
	/**
	 * 导出明细excel
	 * @param query
	 * @return
	 */
	@RequestMapping("exportStockDetail")
	public void exportStockDetail( StockDetailQuery query, HttpServletResponse response){
		//如果是大区先取分页中的数据
		List<StockDetail> list = this.stockService.selectStockDetail(query);
		exportExcel(query, response, list, true);
	}

	/**
	 * 导出excel方法
	 * @param query
	 * @param response
	 * @param list
	 * @param isDetail
	 */
	private void exportExcel(StockDetailQuery query, HttpServletResponse response, List<StockDetail> list, boolean isDetail){
		//导出excel文件
		ExportExcelUtils ex = new ExportExcelUtils();
		String title = getExcelTitle(query);
		//生成日期
		String[] latestDays = DateUtil.getFutureDays(29,Constants.DESC);
		String[] headers = new String[latestDays.length + 1];
		headers[0] = title;
		int j = 1;
		//生成excel头列表
		for (String day : latestDays){
			headers[j++] = day;
		}
		OutputStream fOut = null;
		try {
			// 生成提示信息，
			response.setContentType("application/vnd.ms-excel");
			// 是否是明细
			if (isDetail){
				title = "库存明细-" + title;
			}else{
				title = "库存汇总-" + title;
			}
			// 进行转码，使其支持中文文件名
			String codedFileName = java.net.URLEncoder.encode( title + "统计文档", "UTF-8");
			response.setHeader("content-disposition", "attachment;filename=" + codedFileName + ".xls");
			fOut = response.getOutputStream();
			Field[] fields = getFields(headers, query);
			ex.exportExcel(title, headers, fields, list, fOut, "yyyy-MM-dd");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	private String getExcelTitle(StockDetailQuery query){
		String title = "";
		if (query.getGroupByBranch()){
			title = "房型";
		}else  if(query.getGroupByCategory()){
			title = "品类";
		}else  if(query.getGroupByChannel()){
			title = "渠道";
		}else  if(query.getGroupByRegionname()){
			title = "大区";
		}else  if(query.getGroupByHotle()){
			title = "酒店";
		}
		return title;

	}
	/**
	 * 根据每列字段名称创建需要导出字段的数组
	 *
	 * @param headers
	 * @param query
	 * @return
	 */
	private Field[] getFields(String[] headers, StockDetailQuery query) {
		Field[] fields = new Field[headers.length];
		//获取对象所有的属性值放到集合中
		StockDetail t = new StockDetail();
		Field[] fieldList = t.getClass().getDeclaredFields();
		try {
			if (query.getGroupByBranch()){
				fields[0] = t.getClass().getDeclaredField("branchName");
			}else  if(query.getGroupByCategory()){
				fields[0] = t.getClass().getDeclaredField("categoryName");
			}else  if(query.getGroupByChannel()){
				fields[0] = t.getClass().getDeclaredField("saleChannel");
			}else  if(query.getGroupByRegionname()){
				fields[0] = t.getClass().getDeclaredField("regionname");
			}else  if(query.getGroupByHotle()){
				fields[0] = t.getClass().getDeclaredField("productName");
			}
			int i = 1;
			for (Field field : fieldList) {
				String fieldName = field.getName();
				if(fieldName.startsWith("stock") && !fieldName.equals("stock1")){
					fields[i] = field;
					System.out.println(fieldName);
					i ++;
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return fields;
	}
    /**
     * 各类明细查询
     * @param query
     * @return
     */
    @RequestMapping("searchRedis")
    @ResponseBody
    public BaseResponseVO<StockDetail> searchRedis(@RequestBody StockDetailQuery query){
    	BaseResponseVO<StockDetail> responseVo = new BaseResponseVO<>();
    	try {
    		List<StockDetail> list = this.stockService.selectStockDetailRedis(query);
    		if (list == null || list.size() == 0){
    			responseVo.setCode(0);
    			responseVo.setMessage("数据不存在");
    			return responseVo;
    		}
    		responseVo.setCode(1);
    		responseVo.setDataList(list);
    		return responseVo;
		} catch (Exception e) {
			log.error("detail error:{}" + e.getMessage(), e);
		}
    	responseVo.setCode(0);
		responseVo.setMessage("服务异常");
    	return responseVo;
    }

    /**
     * 各类明细分页查询
     * @param query
     * @return
     */
    @RequestMapping("searchPage")
    @ResponseBody
    public BaseResponseVO<StockDetail> searchPage(@RequestBody StockDetailQuery query){
    	BaseResponseVO<StockDetail> responseVo = new BaseResponseVO<StockDetail>();
    	try {
    		PageInfo<StockDetail> page = this.stockService.selectStockDetailPage(query);
    		if (page == null || page.getList() == null || page.getList().size() == 0){
    			responseVo.setCode(0);
    			responseVo.setMessage("数据不存在");
    			return responseVo;
    		}
    		responseVo.setCode(1);
    		responseVo.setPageInfo(page);
    		return responseVo;
    	} catch (Exception e) {
    		log.error("detail error:{}" + e.getMessage(), e);
    	}
    	
    	responseVo.setCode(0);
		responseVo.setMessage("服务异常");
		return responseVo;
    }

    /**
     * 各类明细分页查询
     * @param query
     * @return
     */
    @RequestMapping("searchPageUtil")
    @ResponseBody
    public BaseResponseVO<StockDetail> searchPageUtil(@RequestBody StockDetailQuery query){
    	BaseResponseVO<StockDetail> responseVo = new BaseResponseVO<StockDetail>();
    	try {
    		PageInfoUtil<StockDetail> page = this.stockService.selectStockDetailPageByRedis(query, 10);
    		if (page == null || page.getList() == null || page.getList().size() == 0){
    			responseVo.setCode(0);
    			responseVo.setMessage("数据不存在");
    			return responseVo;
    		}
    		responseVo.setCode(1);
    		responseVo.setPage(page);
    		return responseVo;
    	} catch (Exception e) {
    		log.error("detail error:{}" + e.getMessage(), e);
    	}

    	responseVo.setCode(0);
		responseVo.setMessage("服务异常");
		return responseVo;
    }

    
    @RequestMapping("productManagerSearch")
    @ResponseBody
    public List<String> productManagerSearch(String regionName) {
    	
    	log.info("productManagerSeach start param regionName=" + regionName);
    	
    	List<String> productManagerNameList = new ArrayList<>();
        //查询产品经理列表
        try {
        	if (regionName == null || "".equals(regionName)){
        		log.error("regionName is null or regionName length is 0");
        		return productManagerNameList;
        	}
        	List<RegionProductManager> productList =  regionProductManagerService.selectProductManagerList(regionName);
            if (productList != null && productList.size() > 0){
             	for (RegionProductManager region : productList){
             		productManagerNameList.add(region.getProductManager());
             	}
            }
            return productManagerNameList;
        }catch (Exception e){
            log.error("detail error:{}" + e.getMessage(), e);
        }
        return new ArrayList<>();
    }
    
    @RequestMapping("supplierNameSearch")
    @ResponseBody
    public List<String> supplierNameSearch() {
    	
    	log.info("supplierNameSeach start");
    	
    	List<String> supplierNameList = new ArrayList<String>();
    	//查询供应商列表
    	try {
    		List<RegionProductManager> supplierList =  regionProductManagerService.selectSupperNameList();
    		if (supplierList != null && supplierList.size() > 0){
    			for (RegionProductManager supplier : supplierList){
    				if (supplier != null && supplier.getSupplierName() != null && !"".equals(supplier.getSupplierName())){
    					supplierNameList.add(supplier.getSupplierName());
    				}
    			}
    		}
    		return supplierNameList;
    	}catch (Exception e){
    		log.error("detail error:{}" + e.getMessage(), e);
    	}
    	return new ArrayList<>();
    }
    @RequestMapping("regionNameSearch")
    @ResponseBody
    public List<String> regionNameSearch() {

		log.info("regionNameSearch start");
		List<RegionProductManager> regionList =  regionProductManagerService.selectRegionList();

    	//查询供应商列表
    	try {
			List<String> regionNameList = new ArrayList<>();
			if (regionList != null && regionList.size() > 0){
				for (RegionProductManager region : regionList){
					if(region == null || region.getRegionName() == null || "".equals(region.getRegionName())){
						continue;
					}
					regionNameList.add(region.getRegionName());
				}
			}
    		return regionNameList;
    	}catch (Exception e){
    		log.error("detail error:{}" + e.getMessage(), e);
    	}
    	return new ArrayList<>();
    }

    @RequestMapping("supplierTypeSearch")
    @ResponseBody
    public List<String> supplierTypeSearch() {
    	
    	log.info("supplierTypeSeach start");
    	
    	List<String> supplierList = new ArrayList<String>();
    	//查询供应商列表
    	try {
    		List<RegionProductManager> supplierTypeList =  regionProductManagerService.selectSupperTypeList();
    		if (supplierTypeList != null && supplierTypeList.size() > 0){
    			for (RegionProductManager supplier : supplierTypeList){
    				if (supplier != null && supplier.getSupplierType() != null && !"".equals(supplier.getSupplierType())){
    					supplierList.add(supplier.getSupplierType());
    				}
    			}
    		}
    		return supplierList;
    	}catch (Exception e){
    		log.error("detail error:{}" + e.getMessage(), e);
    	}
    	return new ArrayList<String>();
    }
    
    
    @RequestMapping("categorySearch")
    @ResponseBody
    public List<String> categorySearch() {
    	
    	log.info("categorySearch start");
    	
    	List<String> categoryNameList = new ArrayList<>();
    	//查询品类
    	try {
    		List<CategoryChannelView> categoryList =  categoryChannelViewService.selectCategoryList();
    		if (categoryList != null && categoryList.size() > 0){
    			for (CategoryChannelView category : categoryList){
    				if (category != null && category.getCategoryName() != null && !"".equals(category.getCategoryName())){
    					categoryNameList.add(category.getCategoryName());
    				}
    			}
    		}
    		return categoryNameList;
    	}catch (Exception e){
    		log.error("detail error:{}" + e.getMessage(), e);
    	}
    	return new ArrayList<>();
    }
    
    @RequestMapping("channelSearch")
    @ResponseBody
    public List<String> channelSearch() {
    	
    	log.info("channelSeach start");
    	
    	List<String> channelNameList = new ArrayList<>();
    	//渠道
    	try {
    		List<CategoryChannelView> channelList =  categoryChannelViewService.selectChannelList();
    		if (channelList != null && channelList.size() > 0){
    			for (CategoryChannelView channel : channelList){
    				if (channel != null && channel.getSaleChannel() != null && !"".equals(channel.getSaleChannel())){
    					channelNameList.add(channel.getSaleChannel());
    				}
    			}
    		}
    		return channelNameList;
    	}catch (Exception e){
    		log.error("detail error:{}" + e.getMessage(), e);
    	}
    	return new ArrayList<>();
    }
    
    @RequestMapping("productSearch")
    @ResponseBody
    public List<String> productSearch() {
    	
    	log.info("productSearch start");
    	
    	List<String> productNameList = new ArrayList<>();
    	//查询酒店
    	try {
    		List<ProductBranchView> productList =  productBranchViewService.selectProductList();
    		if (productList != null && productList.size() > 0){
    			for (ProductBranchView product : productList){
    				if (product != null && product.getProductName() != null && !"".equals(product.getProductName())){
    					productNameList.add(product.getProductName());
    				}
    			}
    		}
    		return productNameList;
    	}catch (Exception e){
    		log.error("detail error:{}" + e.getMessage(), e);
    	}
    	return new ArrayList<>();
    }
    
    @RequestMapping("branchSearch")
    @ResponseBody
    public List<String> branchSearch(@RequestBody StockDetailQuery query ) {
    	
    	log.info("branchSearch start");
    	List<String> branchNameList = new ArrayList<>();
    	//查询房型
    	try {
    		List<ProductBranchView> branchList =  productBranchViewService.selectBranchList(query);
    		if (branchList != null && branchList.size() > 0){
    			for (ProductBranchView branch : branchList){
    				if (branch != null && branch.getBranchName() != null && !"".equals(branch.getBranchName())){
    					branchNameList.add(branch.getBranchName());
    				}
    			}
    		}
    		return branchNameList;
    	}catch (Exception e){
    		log.error("detail error:{}" + e.getMessage(), e);
    	}
    	return new ArrayList<>();
    }
    
    

}
